'''
用户注册相关的功能 注册 登录 注销 短信
'''
from io import BytesIO
from django.views import View
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
from django.http import JsonResponse
from web.forms.account import RegisterModelForm
from web.forms.account import SmsSendModelForm
from web.forms.account import LoignUserPwdModelForm
from web.forms.account import LoginSmsModelForm
from web import models
from django.urls import reverse
from utils.image_code import check_code
from django.db.models import Q
import datetime
import uuid

class RegisterView(View):
    '''
    注册视图
    '''
    def get(self,request):
        form=RegisterModelForm()
        return render(request,'web/register.html',{'form':form})
    def post(self,request):

        form = RegisterModelForm(request.POST)
        if form.is_valid():
            instance=form.save()
            #创建交易记录
            price_policy=models.PricePolicy.objects.filter(category=1,title='个人免费版').first()
            models.Transaction.objects.create(
                user=instance,
                price_policy=price_policy,
                order=str(uuid.uuid4()),
                status=2,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now())
            index_href=reverse('web:index')
            return JsonResponse({'status':True,'data':index_href})
        else:

            return JsonResponse({'status':False,'error':form.errors})


class RSMSView(View):
    '''
    发送短信
    '''
    def get(self,request):

        form=SmsSendModelForm(request,data=request.GET)
        if form.is_valid():

            return JsonResponse({'status':True})
        else:

            return JsonResponse({'status':False,'error':form.errors})


class LoginSmsView(View):
    '''
    短信登录页面
    '''
    def get(self,request):
        form=LoginSmsModelForm()
        return render(request,'web/login_sms.html',{'form':form})
    def post(self,request):
        form=LoginSmsModelForm(data=request.POST)
        if form.is_valid():
            mobile_phone=form.cleaned_data.get('mobile_phone')
            user_obj=models.UserInfo.objects.get(mobile_phone=mobile_phone)
            request.session['user_info']=user_obj.pk
            request.session.set_expiry(60*60*24*14)
            index_href=reverse('web:index')
            return JsonResponse({"status":True,'data':index_href})
        else:
            return JsonResponse({'status':False,'error':form.errors})

class LoginUserPwdView(View):
    '''
    用户名密码登录
    '''
    def get(self,request):
        '''
        用户名密码的显示页面
        :param request:
        :return:
        '''
        form=LoignUserPwdModelForm(request)
        return render(request,'web/login_user_pwd.html',{'form':form})
    def post(self,request):
        '''

        :param request:
        :return:
        '''
        form=LoignUserPwdModelForm(request,data=request.POST)
        if form.is_valid():
            username=form.cleaned_data.get('username')
            password=form.cleaned_data.get('password')
            user_obj=models.UserInfo.objects.filter(Q(email=username)|Q(username=username)|Q(mobile_phone=username)).filter(password=password).first()
            if user_obj:
                request.session['user_info'] = user_obj.pk
                request.session.set_expiry(60 * 60 * 24 * 14)
                return redirect('web:index')
            else:
                form.add_error('username','用户名密码错误')
        return render(request,'web/login_user_pwd.html',{'form':form})

class ImageCodeView(View):
    '''
    获取验证码
    '''
    def get(self,request):
        image_object,code=check_code()
        request.session['image_code']=code
        request.session.set_expiry(60)
        stream=BytesIO()
        image_object.save(stream,'png')
        return HttpResponse(stream.getvalue())

class LayoutView(View):
    def get(self,request):
        request.session.flush()
        return redirect('web:index')